﻿using Daemon.Data.Infrastructure.Auth;
using Daemon.Middleware;
using Daemon.Model;
using Daemon.Repository.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DaemonAPI.Helpers
{
	public class MFAHelper
	{
		internal static string GeneratePin(string email, string prefix, out bool sendSuccess)
		{
			var securityCode = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0)).Next(100000, 999999).ToString();
			sendSuccess = TokenHelper.SendMFACodeWithEmail(email, securityCode, prefix);
			return securityCode;
		}

		internal static bool IsEnableEmailAuth(BaseAuthUser user)
		{
			var clientConfigRepository = ServiceLocator.Resolve<IClientConfigRepository>();
			var clientConfig = clientConfigRepository.Find();

			if (clientConfig.EnableMultifactorAuth
				&& clientConfig.AllowMultifactorAuthEmail
				&& user.UserRoles != null && user.UserRoles.Any(r => r.AdminRole.EnableMultifactorAuth)
				&& !string.IsNullOrEmpty(user.Email))
			{
				return true;
			}

			return false;
		}
	}
}
